import { Article } from "@/apis/shared";
import React, { useState } from "react";
import { Button, List, message } from "antd";
import IconText from "./IconText.tsx";
import { EyeOutlined, LikeFilled, MessageOutlined } from "@ant-design/icons";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { useNavigate, useLocation } from "react-router-dom";
import { useDispatch } from "react-redux";
import { userLikeArticle, userUnLikeArticle } from "@/apis/userApi.ts";
import { setUserLikesListToStore } from "@/store/UserInfo/index.ts";

interface ArticleItemProps {
  item: Article;
  setData?: (updater: (prevData: Article[]) => Article[]) => void;
  showModal?: (articleId: string) => void;
}

const ArticleItem: React.FC<ArticleItemProps> = ({
  item,
  setData,
  showModal,
}) => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const location = useLocation();

  const [userLikesList, setUserLikesList] = useState(
    useSelector((state: RootState) => state.UserInfoStore.userLikesList)
  );

  // 判断是否点赞
  const isLiked = (_id: string, userLikesList: string[]) => {
    return userLikesList.some((item) => item === _id);
  };

  // 处理点击评论跳转的事件
  const handleCommentClick = (_id: string) => {
    navigate(`/layout/article?_id=${_id}`);
  };

  // 处理文章点赞逻辑
  const handleLikeClick = async (_id: string) => {
    console.log("Clicked like");

    // 判断是否点过赞了
    if (isLiked(_id, userLikesList)) {
      console.log("在点赞这里", userLikesList);
      // 点过赞了，取消点赞
      const res = await userUnLikeArticle(_id);

      // 处理后端返回的结果
      if (res.code !== 200) {
        return message.error("取消点赞失败");
      }

      // 取消点赞，更新用户的点赞列表
      // 手动更新userLiskesList
      setUserLikesList((prevLikesList) => {
        return prevLikesList.filter((item) => item !== _id);
      });
      // 手动更新redux store
      dispatch(
        setUserLikesListToStore(userLikesList.filter((item) => item !== _id))
      );
      // 更新data数据
      setData!((prevData) => {
        return prevData.map((aritcle) => {
          if (aritcle._id === _id) {
            return {
              ...aritcle,
              likes: aritcle.likes - 1,
            };
          } else {
            return aritcle;
          }
        });
      });
    } else {
      console.log("在未点赞这里", userLikesList);
      // 未点过赞，点赞
      // 向后端发送文章点赞请求
      const res = await userLikeArticle(_id);

      // 处理后端返回的结果
      if (res.code !== 200) {
        return message.error("点赞失败");
      }

      // 手动点赞，更新用户的点赞列表
      // 手动更新userLikesList
      setUserLikesList((prevLikesList) => {
        return [...prevLikesList, _id];
      });
      // 手动更新redux store
      dispatch(setUserLikesListToStore([...userLikesList, _id]));
      // 更新data数据
      setData!((prevData) => {
        return prevData.map((aritcle) => {
          if (aritcle._id === _id) {
            return {
              ...aritcle,
              likes: aritcle.likes + 1,
            };
          } else {
            return aritcle;
          }
        });
      });
    }
  };

  // 处理文章点击进入事件
  const handleArticleClick = (_id: string) => {
    navigate(`/layout/article?_id=${_id}`)
  }

  /* 
    TODO: 是否可以编辑或者删除文章的逻辑 
  */

  // 获取当前的路由
  const currentPath = location.pathname;

  // 判断是否是用户或者是作者的详情页
  const isUserPage = currentPath.includes("user");

  // 点击编辑按钮
  const handleEditClick = (_id: string) => {
    // 直接跳转路由到编辑页面
    navigate(`/editor?_id=${_id}`);
  };

  const titleStyle: React.CSSProperties = {
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
    // maxWidth: "200px", // 根据需要调整最大宽度
  };

  const summaryStyle: React.CSSProperties = {
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
    // maxWidth: "300px", // 根据需要调整最大宽度
  };

  return (
    <List.Item
      key={item._id}
      data-id={item._id}
      actions={[
        <IconText
          icon={<EyeOutlined />}
          text={item.views.toString()}
          key="list-vertical-star-o"
        />,
        <IconText
          icon={
            <LikeFilled
              style={{
                color: isLiked(item._id, userLikesList) ? "red" : "inherit",
              }}
              onClick={() => {
                handleLikeClick(item._id);
              }}
            />
          }
          text={item.likes.toString()}
          key="list-vertical-like-o"
        />,
        <IconText
          icon={
            <MessageOutlined onClick={() => handleCommentClick(item._id)} />
          }
          text={item.comments.toString()}
          key="list-vertical-message"
        />,
        isUserPage && (
          <Button
            type="link"
            key="edit-button"
            onClick={() => handleEditClick(item._id)}
          >
            编辑
          </Button>
        ),
        isUserPage && (
          <Button
            type="link"
            key="delete-button"
            onClick={() => showModal!(item._id)}
          >
            删除文章
          </Button>
        ),
      ]}
    >
      <List.Item.Meta
        title={
          <div style={titleStyle}>
            <a
              style={{ color: "inherit" }}
              // href={`/layout/article?_id=${item._id}`}
              onClick={() => handleArticleClick(item._id)}
            >
              {item.title}
            </a>
          </div>
        }
        description={<div style={summaryStyle}>{item.summary}</div>}
      />
      作者：
      <a href={`/layout/author?authorEmail=${item.authorEmail}`}>
        {item.authorNickName ? item.authorNickName : item.authorEmail}
      </a>
    </List.Item>
  );
};

export default ArticleItem;
